package cn.com.dragonpass.psystem.common.util;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jetbrains.annotations.NotNull;

import java.util.*;

public class TestExcle {
    public static void main(String[] args) {
        String fileName = "D:\\example.xlsx";
        List<List<String>> data = getData();
        HorizontalCellStyleStrategy specialHorizontalCellStyleStrategy = getSpecialHorizontalCellStyleStrategy();

        ExcelWriter excelWriter = EasyExcel.write(fileName).registerWriteHandler(new CustomRowWriteHandler(0,0,0,2)).registerWriteHandler(new SimpleColumnWidthStyleStrategy(30))
               // .registerWriteHandler(new AutoSizeStrategy())
                .registerWriteHandler(specialHorizontalCellStyleStrategy).build();




        // 写入Excel
        WriteSheet sheet = EasyExcel.write(fileName)
                .sheet("Sheet1").build();
       excelWriter.write(getHead(),sheet);
      //  sheet.setHead(getHead());

        excelWriter.write(data,sheet);
        excelWriter.finish();


//      //  excelWriter.merge(0, 0, 0, 2);

//        ExcelWriterSheetBuilder bu = EasyExcel.write(fileName)
//               .registerWriteHandler(new CustomRowWriteHandler(0,0,0,2))
//                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())  // 设置自适应列宽
//                .registerWriteHandler(new AutoSizeStrategy())  // 设置自动换行
//                .registerWriteHandler(new CellInfo())
//
//                .sheet("Sheet1");
//      //  bu.head(getHead());
//    //  bu.doWrite(getHead());
//        bu.doWrite(data);

//https://blog.csdn.net/qq_46548855/article/details/135817806
    }

    private static List<List<String>> getData() {
        List<List<String>> data = new ArrayList<>();
        data.add(Arrays.asList("币种编码" ,"币种名称 ","汇率 "));
        data.add(Arrays.asList("xxssss，。","yyyyyyysss","xxsssss "));
        return data;
    }

    private static List<List<String>> getHead() {
        List<List<String>> headList =new ArrayList<>();
        List<String> head=new ArrayList<>();



        String msg="1、导入字段说明\n" +
                "（1）币种编码：必填，需大写，如CNY、USD；\n" +
                "（2）币种名称：如人民币、美元等；\n" +
                "（3）汇率：必填，支持小数点后四位，不足四位补0，多余四位采用四舍五入；\n" +
                "2、若对应币种汇率无需更新，模板需要删除该币种数据；\n" +
                "3、以人民币为本位币导入汇率数据；";

        head.add(msg);
        headList.add(head);


        return headList;


    }

    // 自定义的自动换行策略
    public static class AutoSizeStrategy extends AbstractColumnWidthStyleStrategy {


        @Override
        protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {
            if (cell.getRow().getRowNum()==0) {
                System.out.println("自动换行");
                CellStyle cellStyle = cell.getCellStyle();
                cellStyle.setWrapText(true);
                cell.setCellStyle(cellStyle);
            }

        }
    }

    public static class CustomRowWriteHandler implements RowWriteHandler {



        private int firstRow;
        private int lastRow;
        private int firstCol;
        private int lastCol;


        public CustomRowWriteHandler(int firstRow, int lastRow, int firstCol, int lastCol) {
            this.firstRow = firstRow;
            this.lastRow = lastRow;
            this.firstCol = firstCol;
            this.lastCol = lastCol;
        }

        @Override
        public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer integer, Integer integer1, Boolean aBoolean) {
         //   System.out.println("..............");
        }

        @Override
        public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer integer, Boolean aBoolean) {
           // System.out.println("..............*********");
        }

        @Override
        public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
                                    Integer relativeRowIndex, Boolean isHead) {

          //  System.out.println(relativeRowIndex+"------->"+row.getRowNum());
            // 在这里编写你的自定义逻辑
            // 例如，给每一行添加一个公共的背景颜色
            // row.getCell(0).getCellStyle().setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            // row.getCell(0).getCellStyle().setFillPattern(FillPatternType.SOLID_FOREGROUND);


            if ( relativeRowIndex.equals(firstRow)&&row.getRowNum()==0) {
                CellRangeAddress cellRangeAddress = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
                writeSheetHolder.getSheet().addMergedRegion(cellRangeAddress);



            }
            if (relativeRowIndex == 0 &&row.getRowNum()==0) {
                row.setHeight((short) 2500);




            }else{
                Cell cell = row.getCell(0);
                CellStyle cellStyle = cell.getCellStyle();
                cellStyle.setWrapText(true);
                cellStyle.setBorderRight(BorderStyle.THIN);
                cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
                cell.setCellStyle(cellStyle);
            }
        }
    }


    @NotNull
    public static HorizontalCellStyleStrategy getSpecialHorizontalCellStyleStrategy() {
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.TOP);
        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        headWriteCellStyle.setBorderRight(BorderStyle.THIN);
        headWriteCellStyle.setBorderTop(BorderStyle.THIN);

        //内容策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.TOP);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        contentWriteCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        contentWriteCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

        //设置 自动换行
        contentWriteCellStyle.setWrapped(true);
        WriteFont headWriteFont1 = new WriteFont();
//        headWriteFont1.setColor(IndexedColors.RED.index);
        headWriteFont1.setColor(IndexedColors.LIGHT_YELLOW.index);
        contentWriteCellStyle.setWriteFont(headWriteFont1);
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }

    public static class CellInfo implements CellWriteHandler {

        @Override
        public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) {

        }

        @Override
        public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Boolean aBoolean) {

            Map<Integer, Integer> columnWidthMap = new HashMap<>();
            if (aBoolean==true) {


//                columnWidthMap.put(0, 30);
//                writeSheetHolder.getWriteSheet().setColumnWidthMap(columnWidthMap);

                CellStyle cellStyle = cell.getCellStyle();
                cellStyle.setWrapText(true);

                cell.setCellStyle(cellStyle);
                columnWidthMap.put(1, 20);
              writeSheetHolder.getWriteSheet().setColumnWidthMap(columnWidthMap);
            }else{
                System.out.println("---------------cell----------");
                columnWidthMap.put(0, 520);
                writeSheetHolder.getWriteSheet().setColumnWidthMap(columnWidthMap);
            }

        }

        @Override
        public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {

        }
    }

}
